# -*- coding:utf-8 -*-
import sys
import cv2  
import numpy as np 
import pygame
import time
import sys
from pygame.locals import *
from PIL import Image
import tkFileDialog
from tkFileDialog import askdirectory
import shutil
hsv = (0, 0, 0)
cute = not True
def process_img():
    global apple_number,apple_suface
    global deal_flag
    global r,g,b,h,s,v
    deal_flag = True
    global image_path
    global result_image
    print(image_path)
    print(result_save_as_path)
    im = Image.open(image_path)
    (x,y)=im.size
    fazhi = x/14
    y *= 2
    x *= 2
    out = im.resize((x,y))
    out.save('big_image.jpg')
    Img = cv2.imread('big_image.jpg')
    img_size = Img.shape
    kernel_2 = np.ones((2,2),np.uint8)
    kernel_3 = np.ones((3,3),np.uint8)
    kernel_4 = np.ones((4,4),np.uint8)
    if Img is not None:
        HSV = cv2.cvtColor(Img, cv2.COLOR_BGR2HSV) 
        
        h_low=int((h/2)-4)
        if h_low<0:
            h_low=0
        h_upp=int((h/2)+4)
        if h_upp>360:
            h_upp=360
        Lower = np.array([h_low, 46, 46])  
        Upper = np.array([h_upp, 255, 255])
        print(str(h_low)+'-->'+str(h_upp))  
        mask = cv2.inRange(HSV, Lower, Upper)  
        erosion = cv2.erode(mask,kernel_4,iterations = 1)  
        erosion = cv2.erode(erosion,kernel_4,iterations = 1)  
        dilation = cv2.dilate(erosion,kernel_4,iterations = 1)  
        dilation = cv2.dilate(dilation,kernel_4,iterations = 1)  
        target = cv2.bitwise_and(Img, Img, mask=dilation)  
        ret, binary = cv2.threshold(dilation,127,255,cv2.THRESH_BINARY)     
        contours, hierarchy = cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)    
        p=0
        r=0
        l=0
        roi_max_hight =0
        for i in contours:
            x,y,w,h = cv2.boundingRect(i)
            if h>fazhi and w>fazhi:
                if cute:
                    apple=Img[y:y+h,x:x+w]
                    try:
                        Img[l:l+h,r:r+w]=apple
                    except:
                        pass
                    r = r+w+1
                    if roi_max_hight<h:
                        roi_max_hight=h
                    if r+300>img_size[1]:
                        r=0
                        l=roi_max_hight  
                cv2.rectangle(Img,(x,y),(x+w,y+h),(20,20,255),20)   
                #font=cv2.FONT_HERSHEY_SIMPLEX  
                #cv2.putText(Img,str(p),(x-10,y+10), font, 4,(255,255,255),4)
                p +=1
        apple_number = p

        print 'apple number ',p
        #roiImg = Img[50:150,200:300]
        #Img[0:100,0:100] = roiImg 
        cv2.imwrite('result.jpg',Img)
def save_img():
    global result_save_as_path
    try:
        result_save_as_path = askdirectory()
        path = result_save_as_path+'/result.jpg'
        print(path)
        shutil.copy('result.jpg',path)
    except:
        pass
    
def get_img():
    global image_path
    image_path = tkFileDialog.askopenfilename()

def get_preview_show_image(image):
    global image_size_x ,image_size_y, preview_image_size_x, preview_image_size_y
    try:
        im = Image.open(image)
        (x,y)=im.size
        image_size_x ,image_size_y = (x,y)
        if x>y:
            width=410
            y = int(y*width/x)
            x = width
            preview_image_size_x = x
            preview_image_size_y = y
            out = im.resize((x,y))
            out.save('preview_image.jpg')
        else:
            height = 320
            x = int(x*height/y)
            y = height
            preview_image_size_x = x
            preview_image_size_y = y
            out = im.resize((x,y))
            out.save('preview_image.jpg')
    except:
        print('tu pian jia zai shi bai')

def get_result_show_image(image):
    try:
        im = Image.open(image)
        (x,y)=im.size
        if x>y:
            width=410
            y = int(y*width/x)
            x = width
            out = im.resize((x,y))
            out.save('result_image.jpg')
        else:
            height = 320
            x = int(x*height/y)
            y = height
            out = im.resize((x,y))
            out.save('result_image.jpg')
    except:
        print('tupianjiazaishibai')
def select_apple_color(surface):
    global r,g,b,h,s,v, show_r, show_g, show_b
    x, y = pygame.mouse.get_pos()
    r, g, b = surface.get_at((x-40, y-310))[0:3]
    print(r, g, b)
    show_r, show_g, show_b = r,g,b
    r, g, b = r/255.0, g/255.0, b/255.0
    mx = max(r, g, b)
    mn = min(r, g, b)
    df = mx-mn
    if mx == mn:
        h = 0
    elif mx == r:
        h = (60 * ((g-b)/df) + 360) % 360
    elif mx == g:
        h = (60 * ((b-r)/df) + 120) % 360
    elif mx == b:
        h = (60 * ((r-g)/df) + 240) % 360
    if mx == 0:
        s = 0
    else:
        s = df/mx
    v = mx
    
    #hsv = h, s, v
    print('hsv ->'+str(h/2)+str(s*255)+str(v*255))
def current_path():
    path = str(sys.path[0])+'\\'
    return path
def get_resolution():
    return pygame.display.list_modes()[0]
set_title_bar_position = 90,3
set_exit_bar_position = 1290, 10
set_result_bar_position = 930,455
set_preview_bar_position = 250,420
set_preview_image_position = 40,310#（x, y）
set_select_image_bar_position = 270,208
set_dispose_image_bar_position = 930,410
set_result_image_position = 600,305
set_apple_suface_position = 1210,315
set_apple_color_position = 1090,415
set_size_x_position = 1210,470
set_size_y_position = 1210,525
image_path = 'tree.jpg'
result_path = 'result.jpg'
preview_image_file = 'preview_image.jpg'
result_image_file= 'result_image.jpg'
result_save_as_path = None
deal_flag = not True
apple_number = 0
r, g, b = 0, 0, 0
h, s, v = 0, 0, 0
show_r, show_g, show_b = 0, 0, 0
image_size_x ,image_size_y = 0,0
preview_image_size_x, preview_image_size_y = 0, 0

pygame.init()
font = pygame.font.Font(None, 45)
apple_suface = font.render(str(apple_number),True,(255,0,0))
color = pygame.font.Font(None, 45)
apple_color = color.render('('+str(r)+','+str(g)+','+str(b)+')',True,(255,0,0))

size_xx = pygame.font.Font(None, 45)
size_x = size_xx.render(str(image_size_x),True,(255,0,0))
size_yy = pygame.font.Font(None, 45)
size_y = size_yy.render(str(image_size_y),True,(255,0,0))


clock = pygame.time.Clock()
width, height = get_resolution()
width, height = width-20, height-100
screen = pygame.display.set_mode(get_resolution())#(width, height), FULLSCREEN | HWSURFACE
pygame.display.set_caption('果实信息提取器')

background = pygame.image.load('bg.png').convert()
preview_bar =  pygame.image.load('tupianyulanlan.png')
preview_bar_position = preview_bar.get_rect()
preview_bar_position.center = set_preview_bar_position

result_bar = pygame.image.load('chulijieguolan.png')
result_bar_position = result_bar.get_rect()
result_bar_position.center = set_result_bar_position
select_image_bar = pygame.image.load('xuantuanniu.png')
select_image_bar_position = select_image_bar.get_rect()
select_image_bar_position.center = set_select_image_bar_position
dispose_image_bar = pygame.image.load('chulianniu.png')
dispose_image_bar_position = dispose_image_bar.get_rect()
dispose_image_bar_position.center = set_dispose_image_bar_position
get_preview_show_image(image_path)
preview_image = pygame.image.load(preview_image_file)
preview_image_position = preview_image.get_rect()
preview_image_position = set_preview_image_position

get_result_show_image(result_path)#current_path()+
result_image = pygame.image.load(result_image_file)#current_path()+
result_image_position = result_image.get_rect()
result_image_position = set_result_image_position

title_bar = pygame.image.load('biaoti.png')
title_bar_position = title_bar.get_rect()
title_bar_position = set_title_bar_position

exit_bar = pygame.image.load('exit.png')
exit_bar_position = exit_bar.get_rect()
exit_bar_position = set_exit_bar_position

image_path_copy = image_path
print(image_path)
while True:

    for event in pygame.event.get():
        #print(str(event)+'\n')#输出所有事件，包括鼠标动一下，键盘动一下啥的，就是刚才的坐标，注释掉就不输出了
        if event.type == QUIT:
            sys.exit()
        if event.type == MOUSEBUTTONDOWN:
            x, y = pygame.mouse.get_pos()
            if 300<x<480 and 190<y<260:
                get_img()
            if 40<x<(40+preview_image_size_x) and 313<y<(313+preview_image_size_y):
                select_apple_color(preview_image)
                apple_color = color.render('('+str(show_r)+','+str(show_g)+','+str(show_b)+')',True,(255,0,0))
                apple_color_position = apple_color.get_rect()
                apple_color_position.center = set_apple_color_position

                
            if 810<x<1010 and 190<y<260:
                process_img()
            if 1070<x<1280 and 190<y<260:
                save_img()
            if 1290<x<1390 and 10<y<110:
                sys.exit()
            print('x ->'+str(x))
            print('y ->'+str(y))
            
        if event.type == MOUSEBUTTONUP:
            print('botton up')
            
        if event.type == KEYDOWN:
            if event.key == K_q:
                sys.exit()
            if event.key == K_LEFT:
                pass
            if event.key == K_RIGHT:
                pass
            if event.key == K_UP:
                pass
            if event.key == K_DOWN:
                pass

    if image_path_copy != image_path:
        print('file changed')
        image_path_copy = image_path
        get_preview_show_image(image_path)
        preview_image = pygame.image.load(preview_image_file)
        preview_image_position = preview_image.get_rect()
        preview_image_position = set_preview_image_position
    if deal_flag:
        deal_flag = not True
        get_result_show_image(result_path)
        result_image = pygame.image.load(result_image_file)
        result_image_position = result_image.get_rect()
        result_image_position = set_result_image_position

        apple_suface = font.render(str(apple_number),True,(255,0,0))
        apple_suface_position = apple_suface.get_rect()
        apple_suface_position.center = set_apple_suface_position

        size_x = size_xx.render(str(image_size_x),True,(255,0,0))
        size_x_position = size_x.get_rect()
        size_x_position.center = set_size_x_position

        size_y = size_yy.render(str(image_size_y),True,(255,0,0))
        size_y_position = size_y.get_rect()
        size_y_position.center = set_size_y_position
        
    screen.blit(background, (0, 0))
    screen.blit(title_bar,title_bar_position)
    screen.blit(select_image_bar,select_image_bar_position)
    screen.blit(dispose_image_bar,dispose_image_bar_position)
    screen.blit(preview_image, preview_image_position)
    screen.blit(result_image, result_image_position)
    screen.blit(apple_suface, set_apple_suface_position)
    screen.blit(size_x, set_size_x_position)
    screen.blit(size_y, set_size_y_position)
    screen.blit(apple_color, set_apple_color_position)
    screen.blit(result_bar, result_bar_position)
    screen.blit(preview_bar, preview_bar_position)
    screen.blit(exit_bar, set_exit_bar_position)
    pygame.draw.rect(screen, (show_r,show_g,show_b),[1210, 374, 90, 20])
    
    pygame.display.flip()
    clock.tick(20)
